package o2o.web.actions.print;

import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.*;
import o2o.cache.print.PrintConfigMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.print.PrintConfig;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.sys.SysCustomerInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.print.PrintConfigVO;
import o2o.web.actions.user.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PrintConfigAction {

    @RequestMapping("/print/config/get")
    public String print_config_get(String token) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您不是商户");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (shopInfo == null) {
            return AjaxResult.errorResult("店铺不存在，请核实");
        }

        PrintConfig printConfig = PrintConfigMemory.getInstance().getPrintConfigByShopId(shopInfo.getId());
        if (printConfig != null) {
            PrintConfigVO printConfigVO = new PrintConfigVO();
            try {
                ObjectUtils.copyPropertiesExclude(printConfig, printConfigVO);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("获取失败，请稍后重试");
            }
            return AjaxResult.successResult(printConfigVO);
        }
        return AjaxResult.successResult();
    }

    // 添加或者更新 飞鹅配置信息
    @RequestMapping("/print/config/add-update")
    public String print_config_add_update(String token, PrintConfig printConfig) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您不是商户");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (shopInfo == null) {
            return AjaxResult.errorResult("店铺不存在，请核实");
        }
        if (ValidateUtil.isNotID(printConfig.getShopId())) {
            return AjaxResult.errorResult("店铺id不能为空");
        }
        if (ValidateUtil.isNull(printConfig.getFeUser())) {
            return AjaxResult.errorResult("飞鹅打印机的注册名不能为空");
        }

        if (ValidateUtil.isNull(printConfig.getFeUKey())) {
            return AjaxResult.errorResult("飞鹅打印机的ukey不能为空");
        }
        // 检测用户是否在上面注册了啊
        boolean flag = PrintMan.isAlreadyRegistered(printConfig.getFeUser(), printConfig.getFeUKey());
        if (!flag) {
            return AjaxResult.errorResult("你输入的账户未在飞鹅上注册");
        }
        // 检测注册还是添加
        PrintConfig printConfigDB = PrintConfigMemory.getInstance().getPrintConfigByShopId(shopInfo.getId());
        if (printConfigDB == null) {
            // 添加
            long cTime = DateUtils.getCurrTime();
            printConfig.setCreateTime(cTime).setCreateUser(user.getUsername()).setDelFlag(0).setShopId(shopInfo.getId());
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.PRINT_CONFIG, printConfig);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("添加失败，请稍后重试");
            }
            // 缓存
            PrintConfigMemory.getInstance().add(cTime);
        } else {
            String note = "";
            if (!ValidateUtil.isNull(printConfig.getNote())) {
                note = ",note = '" + printConfig.getNote() + "' ";
            }
            // 更新
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.PRINT_CONFIG).append(" set ")
                    .append(" updateUser = '").append(user.getUsername()).append("'")
                    .append(",feUser = '").append(printConfig.getFeUser()).append("'")
                    .append(",feUKey = '").append(printConfig.getFeUKey()).append("'")
                    .append(note)
                    .append(" where ").append(" shopId =").append(shopInfo.getId())
                    .append(" and delFlag = 0");
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("更新失败，请稍后重试");
            }
            // 更新缓存
            PrintConfigMemory.getInstance().modify(shopInfo.getId());
        }
        return AjaxResult.successResult();
    }

    @RequestMapping("/base/print/config/get")
    public String base_print_config_get(String apiKey, String sysAppKey) {
        try {
            String decrypt = EncrypAES.aesDecrypt(apiKey, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }
            SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }

        PrintConfig printConfig = PrintConfigMemory.getInstance().getPrintConfigByShopId(-1L);
        if (printConfig != null) {
            PrintConfigVO printConfigVO = new PrintConfigVO();
            try {
                ObjectUtils.copyPropertiesExclude(printConfig, printConfigVO);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("获取失败，请稍后重试");
            }
            return AjaxResult.successResult(printConfigVO);
        }
        return AjaxResult.successResult();
    }

    // 添加或者更新 base系统管理 打印机配置
    @RequestMapping("/base/print/config/add-update")
    public String base_print_config_add_update(String apiKeyUrl, String sysAppKey, PrintConfig printConfig) {

        try {
            String decrypt = EncrypAES.aesDecrypt(apiKeyUrl, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }
            SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        if ((ValidateUtil.isNull(printConfig.getFeUser()) || ValidateUtil.isNull(printConfig.getFeUKey()))
                &&
                (ValidateUtil.isNull(printConfig.getPartner()) || ValidateUtil.isNull(printConfig.getApiKey()) || ValidateUtil.isNull(printConfig.getEyUsername()))) {
            return AjaxResult.errorResult("信息不全,重新设置");
        }
        // if (ValidateUtil.isNull(printConfig.getFeUser())) {
        //     return AjaxResult.errorResult("飞鹅打印机的注册名不能为空");
        // }
        // if (ValidateUtil.isNull(printConfig.getFeUKey())) {
        //     return AjaxResult.errorResult("飞鹅打印机的ukey不能为空");
        // }
        // if (ValidateUtil.isNull(printConfig.getPartner())) {
        //     return AjaxResult.errorResult("易云联用户id不能为空");
        // }
        // if (ValidateUtil.isNull(printConfig.getApiKey())) {
        //     return AjaxResult.errorResult("易云联用户API 密钥不能为空");
        // }
        // if (ValidateUtil.isNull(printConfig.getEyUsername())) {
        //     return AjaxResult.errorResult("易云联用户用户名不能为空");
        // }
        if (ValidateUtil.isNull(printConfig.getFeUser()) && ValidateUtil.isNull(printConfig.getFeUKey())) {
            // 检测用户是否在上面注册了啊
            boolean flag = PrintMan.isAlreadyRegistered(printConfig.getFeUser(), printConfig.getFeUKey());
            if (!flag) {
                return AjaxResult.errorResult("你输入的账户未在飞鹅上注册");
            }
        }
        // 检测注册还是添加
        PrintConfig printConfigDB = PrintConfigMemory.getInstance().getPrintConfigByShopId(-1L);
        if (printConfigDB == null) {
            // 添加
            long cTime = DateUtils.getCurrTime();
            printConfig.setCreateTime(cTime).setCreateUser("admin").setDelFlag(0).setShopId(-1L);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.PRINT_CONFIG, printConfig);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("添加失败，请稍后重试");
            }
            // 缓存
            PrintConfigMemory.getInstance().add(cTime);
        } else {
            String note = "";
            if (!ValidateUtil.isNull(printConfig.getNote())) {
                note = ",note = '" + printConfig.getNote() + "' ";
            }
            // 更新
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.PRINT_CONFIG).append(" set ")
                    .append(" updateUser = '").append("admin").append("' ");
            if (ValidateUtil.isNotNull(printConfig.getFeUser())) {
                sql.append(",feUser = '").append(printConfig.getFeUser()).append("'");
            }
            if (ValidateUtil.isNotNull(printConfig.getFeUKey())) {
                sql.append(",feUKey = '").append(printConfig.getFeUKey()).append("'");
            }
            if (ValidateUtil.isNotNull(printConfig.getPartner())) {
                sql.append(",partner = '").append(printConfig.getPartner()).append("'");
            }
            if (ValidateUtil.isNotNull(printConfig.getApiKey())) {
                sql.append(",apiKey = '").append(printConfig.getApiKey()).append("'");
            }
            if (ValidateUtil.isNotNull(printConfig.getEyUsername())) {
                sql.append(",EyUsername = '").append(printConfig.getEyUsername()).append("'");
            }
            sql.append(note)
                    .append(" where ").append(" shopId =").append(-1L)
                    .append(" and delFlag = 0");
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("更新失败，请稍后重试");
            }
            // 更新缓存
            PrintConfigMemory.getInstance().modify(-1L);
        }
        return AjaxResult.successResult();
    }
}
